import json
from math import ceil
from typing import List

import pandas
import requests
from PyQt5 import QtCore
from PyQt5.QtCore import QThread
import akshare as ak
from urllib3.exceptions import ReadTimeoutError

from utils.BaseSignal import BaseSignal


class ThreadUpdateWidget(QThread, BaseSignal):
    signalWidgetRowChangeColor = QtCore.pyqtSignal(int, str)

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.rowsPerPage = 20
        self.curPage = 0
        self.stockDF: pandas.DataFrame = pandas.DataFrame()
        self.update = True
        self.m = 0
        self.n = 0
        self.maxPage = 0
        self.selfSelect: List[str] = list()

    def run(self) -> None:
        # Init
        if self.update:
            self.stockDF = ak.stock_zh_a_spot_em().dropna().drop(columns='序号')
            # 股票行列数
            self.m, self.n = self.stockDF.shape
            self.signalSetStockWidget.emit(self.rowsPerPage, self.n, self.stockDF.columns.tolist())
            # 最大页码数
            self.maxPage = ceil(self.m / self.rowsPerPage)

        self.signalShowPermMessage.emit(f"第{self.curPage+1}/{self.maxPage}页")
        # 当前页的第一行在数据集中的偏移
        offset = self.curPage * self.rowsPerPage

        # 更新界面
        for i in range(self.rowsPerPage):
            for j in range(self.n):
                if self.isInterruptionRequested():
                    return
                self.signalAddStockToWidget.emit(i, j, str(self.stockDF.values[offset + i][j]))
            # 如果添加了自选，则将该行设为绿色
            if self.stockDF.values[offset+i][0] in self.selfSelect:
                self.signalWidgetRowChangeColor.emit(i, '#00ae9d')
            # 更新进度条
            self.signalUpdateProgressBar.emit((i + 1) / self.rowsPerPage * 100)
        self.signalUpdateProgressBar.emit(100)


class ThreadUpdateZhWidget(QThread, BaseSignal):
    signalUpdateWindow = QtCore.pyqtSignal(list)

    def __init__(self, parent=None):
        super(ThreadUpdateZhWidget, self).__init__(parent)
        self.data = list()
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE '
        }

    def run(self) -> None:
        """
        调接口获取上证指数，深证成指
        :return:
        """
        try:
            res = requests.get(
                "https://push2.eastmoney.com/api/qt/ulist/get?fields=f12,f13,f14,f1,f2,f4,f3&secids=1.000001,"
                "0.399001&pn=1&np=1",
                headers=self.headers)
            js = json.loads(res.text)
            self.data = js['data']['diff']
            self.signalUpdateWindow.emit(self.data)
        except requests.exceptions as e:
            print(e)
